import router from "@/routes";
// @ts-ignore
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { useUserStore } from "./store/modules/user";
import pinia from "./store/index";
import setting from "./layout/setting";

nprogress.configure({ showSpinner: false });
nprogress.configure({ minimum: 0.1 });
// 路由鉴权引入小仓库也需要引入大仓库
let userStore = useUserStore(pinia);

router.beforeEach(async (to, from, next) => {
    // to and from are both route objects. must call `next`.
    document.title = `${setting.title} -- ${to.meta.title}`;
    // 加载进度条
    nprogress.start();
    /* 
        路由鉴权
            1. 带有token （不可以跳转登录页面）
            2. 未带有token(未登录 除登录界面不可登录其他页面)
    */
    let hasToken = userStore.token;
    let userName = userStore.userName;
    if (hasToken) {
        if (to.path == "/login") {
            next({ path: from.path });
        } else {
            if (userName) {
                next();
            } else {
                try {
                    await userStore.userInfo()
                    // 如果是异步路由 加载完毕后再放行
                    next({...to})
                } catch (error) {
                    // token过期或手动修改token
                    userStore.backLogin();
                    next({path:"/login",query:{redirect:from.path}})
                }
            }
        }
    } else {
        if (to.path == "/login") {
            next();
        } else {
            next({ path: "/login", query: { redirect: to.path } });
        }
    }

    // next()
});

router.afterEach((to, from) => {
    // to and from are both route objects.
    nprogress.done();
});
